<template>
  <view class="index">
    <!-- 选项卡头部 -->
    <scroll-view scroll-x="true" class="tab-header" scroll-with-animation>
      <view
        v-for="(item, index) in tabs"
        :key="index"
        class="tab-item"
        :class="{ active: currentTab === index }"
        @tap="switchTab(index)"
      >
        {{ item.title }}
      </view>
    </scroll-view>
    <view class="square-content">
      <!-- 使用scroll-view组件实现自定义下拉刷新 -->
      <scroll-view
        scroll-y="true"
        class="scroll-content"
        :refresher-enabled="true"
        :refresher-threshold="45"
        :refresher-background="'#f6f8fa'"
        refresher-default-style="black"
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
        @refresherpulling="onPulling"
        @refresherrestore="onRestore"
        @refresherabort="onAbort"
        @scrolltolower="loadMore"
      >
        <view class="cont" v-show="list.length > 0">
          <view
            v-for="item in list"
            :key="item.articleId"
            class="card"
            @click="goDetail(item.articleId)"
          >
            <image
              class="card-avatar"
              :src="globalData.OSS_URL + item.mainImg"
              mode="aspectFill"
            ></image>
            <view class="card-header-title">
              <text class="title">{{ item.title }}</text>
            </view>
          </view>
        </view>
        <view v-if="list.length === 0" class="empty-state">
          <text class="empty-text">暂无数据</text>
        </view>
        <view v-if="isLoading && !isRefreshing" class="loading-more"
          >加载中...</view
        >
        <view v-if="noMoreData && list.length > 0" class="no-more"
          >没有更多数据了</view
        >
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onBeforeMount } from "vue";
import api from "@/utils/api.js";
import { globalData } from "@/utils/util";
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';

const list = ref([]);
const curPage = ref(1);
const currentTab = ref(0); // 当前选中索引,0新闻，1文章
const isLoading = ref(false);
const noMoreData = ref(false); // 是否没有更多数据
const isRefreshing = ref(false); // 是否正在刷新
const totalCount = ref(0); // 总记录数

const tabs = [{ title: "新闻" }, { title: "招聘" }];

const switchTab = (index) => {
  if (currentTab.value === index) return;
  currentTab.value = index;
  resetData();
  getData();
};

onBeforeMount(() => {
  getData();
});

// 重置数据
const resetData = () => {
  curPage.value = 1;
  noMoreData.value = false;
  list.value = [];
  totalCount.value = 0;
};

// 下拉中
const onPulling = () => {
  console.log("下拉中...");
};

// 刷新被中止
const onAbort = () => {
  console.log("刷新被中止");
  isRefreshing.value = false;
};

// 刷新复位
const onRestore = () => {
  console.log("刷新复位");
  isRefreshing.value = false;
};

// 下拉刷新处理
const onRefresh = async () => {
  console.log("触发下拉刷新");
  if (isLoading.value) {
    isRefreshing.value = false;
    return;
  }

  isRefreshing.value = true;
  resetData();

  try {
    await getData();
  } catch (error) {
    console.error("刷新数据失败:", error);
  } finally {
    // 确保无论如何都会结束刷新状态
    setTimeout(() => {
      isRefreshing.value = false;
      console.log("刷新结束");
    }, 500);
  }
};

// 加载更多
const loadMore = () => {
  if (isLoading.value || noMoreData.value) return;

  // 检查是否已加载全部数据
  if (list.value.length >= totalCount.value && totalCount.value > 0) {
    noMoreData.value = true;
    return;
  }

  curPage.value++;
  getData();
};

const getData = async () => {
  if (isLoading.value) return; // 防止重复加载

  isLoading.value = true;
  try {
    const result = await api.articleList({
      curPage: curPage.value,
      pageSize: 10,
      catType: currentTab.value === 0 ? 0 : 1,
    });

    if (result.code === 0) {
      // 保存总记录数
      totalCount.value = result.data.recordCount || 0;

      // 第一页直接替换，其他页追加
      if (curPage.value === 1) {
        list.value = result.data.itemLst || [];
      } else {
        // 如果返回的数据为空数组，标记没有更多数据
        if (!result.data.itemLst || result.data.itemLst.length === 0) {
          noMoreData.value = true;
        } else {
          list.value = [...list.value, ...result.data.itemLst];
        }
      }

      // 检查是否已加载全部数据
      if (list.value.length >= totalCount.value && totalCount.value > 0) {
        noMoreData.value = true;
      }
    } else {
      console.log("请求失败", result.message || "未知错误");
      uni.showToast({
        title: "加载失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.log("请求失败", error);
    uni.showToast({
      title: "网络异常",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }

  return Promise.resolve(); // 确保返回Promise以便于await
};

const goDetail = (articleId) => {
  uni.navigateTo({
    url: `/pages/noteDetail/noteDetail?articleId=${articleId}`,
  });
};

// 分享给朋友
onShareAppMessage(() => {
  return {
    title: '飞手之家 - 新闻动态',
    path: '/pages/square/square',
    imageUrl: '/static/images/head.jpg'
  };
});

// 分享到朋友圈
onShareTimeline(() => {
  return {
    title: '飞手之家 - 新闻动态',
    query: '',
    imageUrl: '/static/images/head.jpg'
  };
});
</script>

<style scoped lang="scss">
.index {
  background-color: #f6f8fa;
  min-height: 100vh;
  width: 100%;
  overflow-x: hidden;
}

.tab-header {
  white-space: nowrap;
  background-color: #fff;
  padding: 0;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 999;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
  display: flex;
  height: 88rpx;
}

.square-content {
  padding-top: 88rpx;
  box-sizing: border-box;
  width: 100%;
//   height: calc(100vh - 88rpx);
}

.scroll-content {
  height: 100%;
  width: 100%;
}

.tab-item {
  display: inline-block;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
  color: #666;
  transition: color 0.3s;
  margin: 0;
  text-align: center;
  width: 50%;
  position: relative;

  &.active {
    color: #2cbaff;
    font-weight: bold;

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 4rpx;
      background-color: #2cbaff;
      border-radius: 2rpx;
    }
  }
}

.cont {
  padding: 20rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
  box-sizing: border-box;
}

.card {
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  width: 48.5%;
  margin-bottom: 20rpx;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  transition: transform 0.2s;

  &:active {
    transform: scale(0.98);
  }
}

.card-avatar {
  width: 100%;
  height: 200rpx;
  object-fit: cover;
}

.card-header-title {
  padding: 16rpx;
  height: 94rpx;
  box-sizing: border-box;
  .title {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    font-size: 26rpx;
    color: #333;
    line-height: 30rpx;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

.loading-more,
.no-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 24rpx;
  width: 100%;
}
</style>
